﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Telerik.Web.Mvc.UI;
using Century.Model;
using Century.Web.UI.MVC;
using Century.Model.ViewModel;
using Century.EnterpriseLibrary.Configuration;
using Century.Business;
using Century.Admin.Models;
using Century.Model.CMS;
using System.Collections;
using Century.Business.CMS;

namespace Century.Admin.Controllers
{
    /// <summary>
    /// Site Tree Controller : Left side tree control
    /// </summary>
    public class SiteTreeController : CenturyAdminBaseController
    {

        public SiteTreeController(ISiteService siteService) : base(siteService) { }

        //string icon_plugin = "/Areas/Admin/Content/Themes/Admin/img/sitetree/plugin.png";
        //string icon_site = "/Areas/Admin/Content/Themes/Admin/img/sitetree/site_tree.png";
        string icon_page
        {
            get
            {
                return IsScriptManagerMode ? "/Areas/Admin/Content/Themes/Admin/img/sitetree/script_code.png" : "/Areas/Admin/Content/Themes/Admin/img/sitetree/page_white_world.png";
            }
        }
        string icon_homepage = "/Areas/Admin/Content/Themes/Admin/img/sitetree/page_white_star.png";
        string icon_page_notpublished = "/Areas/Admin/Content/Themes/Admin/img/sitetree/page_red.png";

        public bool IsScriptManagerMode
        {
            get
            {
                return (ControllerContext.ParentActionViewContext != null && ControllerContext.ParentActionViewContext.RouteData.Values["controller"].ToString() == "CountrySiteScript");
            }
        }

        public ActionResult Index()
        {
            SiteTreeViewModel model = new SiteTreeViewModel();
            //model.Token = Token;
            if (System.Web.HttpContext.Current.Session["CurrentSiteId"] != null && Token.CurrentSite.Id != (int)System.Web.HttpContext.Current.Session["CurrentSiteId"])
            {
                Token.CurrentSite = siteService.GetSites().First(c => c.Id == (int)System.Web.HttpContext.Current.Session["CurrentSiteId"]);
            }
            model.NodeItems = new List<TreeViewItemModel>();

           
            Site site = FrameworkToken.UserToken.CurrentSite;// siteService.GetSites();
           
           
                TreeViewItemModel siteNode = new TreeViewItemModel
                    {
                        Text = site.Name + " - " + site.Path,
                        Value = "CS-" + site.Id.ToString(),
                        LoadOnDemand = true,
                        //HtmlAttributes = new Dictionary<string, string>(temp),
                        ImageUrl = "~/Areas/Admin/Content/Themes/Admin/img/sitetree/site_tree.png"
                    };
                model.NodeItems.Add(siteNode);
                siteNode.Items.AddRange(GetTreeNodesOnDemand(site.Id));

            


            return View(model);// model.NodeItems.AddRange(GetSitePages(Token.CurrentSite.Id));
            //}

            //return View(new List<Site>());
        }

        public List<TreeViewItemModel> GetTreeNodesOnDemand(int siteId)
        {
            List<SitePage> pages = siteService.GetSitePages(siteId);
            //NorthwindDataContext northwind = new NorthwindDataContext();
            //int? parentId = !string.IsNullOrEmpty(node.Value) ? (int?)Convert.ToInt32(node.Value) : null;
            Dictionary<string, string> temp = new Dictionary<string, string>();
            temp.Add("id", "first-item-image");
            //temp.Add("class", "SP-ITEM");

            List<TreeViewItemModel> nodes = pages.OrderBy(c=>c.NodeOrder).Where(c=>!c.ParentId.HasValue).Select(item => new TreeViewItemModel
                                {
                                    Text = item.Name + " (" + item.LocalName + ")",
                                    Value = string.Format("P-{0}", item.Id.ToString()),
                                    LoadOnDemand = false,// item.Employees.Count > 0,
                                    Enabled = true,
                                    ImageUrl = item.IsPublished ? (item.IsHomePage ? icon_homepage : icon_page) : icon_page_notpublished,
                                    HtmlAttributes = new Dictionary<string, string>(temp),
                                    NavigateUrl = Url.Action("Get", "PageManagement", new { id = item.Id, area = "Admin" }),
                                    Items = GetSubPages(item, pages)
                                }).ToList();
           
            return nodes;
            //IsScriptManagerMode ? Url.Action("PageScript", "CountrySiteScript", new { id = item.Id, area = "Admin" }) :
            //  .ItemAction(z => z.Action("ItemDetail", "SiteTree", new { val = z.Value }))
            //.ItemAction(z => z.HtmlAttributes.Add("class", z.Value.Contains("CS") ? "CS-ITEM" : z.Value.Contains("P") ? string.Format("SP-ITEM", z.Value) : string.Empty))
            //return new JsonResult { Data = nodes };
            //return View(new JsonResult { Data = new TreeViewItemModel() });
        }

        private List<TreeViewItemModel> GetSubPages(SitePage item, List<SitePage> pages)
        {
            Dictionary<string, string> temp = new Dictionary<string, string>();
            temp.Add("id", "first-item-image");

            List<TreeViewItemModel> nodes = pages.OrderBy(c => c.NodeOrder).Where(c => c.ParentId == item.Id).Select(pg => new TreeViewItemModel
            {
                Text = pg.Name + " (" + pg.LocalName + ")",
                Value = string.Format("P-{0}", pg.Id.ToString()),
                LoadOnDemand = false,// item.Employees.Count > 0,
                Enabled = true,
                ImageUrl = pg.IsPublished ? (pg.IsHomePage ? icon_homepage : icon_page) : icon_page_notpublished,
                HtmlAttributes = new Dictionary<string, string>(temp),
                NavigateUrl = Url.Action("Get", "PageManagement", new { id = pg.Id, area = "Admin" }),
                Items = GetSubPages(pg, pages)
            }).ToList();
            return nodes;
        }

        //protected TreeViewItemModel GenerateTreeViewNodesForPage(SitePage parentPage)
        //{
        //    TreeViewItemModel node = new TreeViewItemModel();
        //    //List<SitePage> pages = PersistData.AvailablePages.Where(s => s.ParentId == parentPage.Id && s.DraftSourcePageId <= 0).OrderBy(s => s.NodeOrder).ToList();
        //    //if (PersistData.AvailablePages.Any(s => s.ParentId == parentPage.Id))
        //    //{
        //    //    node.Items = new List<TreeViewItemModel>();
        //    //    node.HtmlAttributes["id"] = "first-item-image";
        //    //    node.Text = parentPage.Name;
        //    //    node.Value = string.Format("P-{0}", parentPage.Id.ToString());
        //    //    node.ImageUrl = parentPage.IsPublished ? (parentPage.IsHomePage ? icon_homepage : icon_page) : icon_page_notpublished;
        //    //    if (IsScriptManagerMode)
        //    //    {
        //    //        node.NavigateUrl = Url.Action("PageScript", "CountrySiteScript", new { id = parentPage.Id , area="Admin" });
        //    //    }
        //    //    else
        //    //    {
        //    //        node.NavigateUrl = Url.Action("Get", "PageManagement", new { id = parentPage.Id, area = "Admin" });
        //    //    }

        //    //    foreach (SitePage page in pages)
        //    //    {
        //    //        node.Items.Add(GenerateTreeViewNodesForPage(page));
        //    //    }
        //    //}
        //    //else
        //    //{
        //    //    node = new TreeViewItemModel
        //    //    {
        //    //        Text = parentPage.Name,
        //    //        Value = string.Format("P-{0}", parentPage.Id.ToString()),
        //    //        ImageUrl = parentPage.IsPublished ? (parentPage.IsHomePage ? icon_homepage : icon_page) : icon_page_notpublished,
        //    //        NavigateUrl = (IsScriptManagerMode) ? Url.Action("PageScript", "CountrySiteScript", new { id = parentPage.Id, area = "Admin" }) : Url.Action("Get", "PageManagement", new { id = parentPage.Id, area = "Admin" })
        //    //    };
        //    //    node.HtmlAttributes["id"] = "first-item-image";
        //    //}
        //    return node;
        //}

        //protected List<TreeViewItemModel> GetSitePages(int countrySiteId)
        //{
        //    Dictionary<string, string> htmlAttr = new Dictionary<string, string>();
        //    htmlAttr.Add("class", "t-state-selected");

        //    List<TreeViewItemModel> items = null;// PersistData.AvailableSites.ToList()
        //    //.Where(p => p.Id == countrySiteId)
        //    //.Select(c => new TreeViewItemModel
        //    //{
        //    //    Text = c.Name,
        //    //    Value = string.Format("CS-{0}", c.Id.ToString()),
        //    //    ImageUrl = icon_site,
        //    //    NavigateUrl = (IsScriptManagerMode) ? Url.Action("PageScript", "CountrySiteScript", new { area = "Admin" }) : Url.Action("Index", "SiteManagement", new { area = "Admin" }),
        //    //    Items = (
        //    //                PersistData.AvailablePages.Where(x => x.CountrySiteId == c.Id && x.ParentId == null && x.DraftSourcePageId <= 0)
        //    //                .OrderBy(x => x.NodeOrder)
        //    //                .Select(
        //    //                            x => new TreeViewItemModel
        //    //                            {
        //    //                                Checked = true,
        //    //                                Text = x.Name,
        //    //                                Value = string.Format("P-{0}", x.Id.ToString()),
        //    //                                ImageUrl = x.IsPublished ? (x.IsHomePage ? icon_homepage : icon_page) : icon_page_notpublished,
        //    //                                Items = GenerateTreeViewNodesForPage(x).Items,
        //    //                                NavigateUrl = (IsScriptManagerMode) ? Url.Action("PageScript", "CountrySiteScript", new { id = x.Id, area = "Admin" }) : Url.Action("Get", "PageManagement", new { id = x.Id, area = "Admin" })
        //    //                            }
        //    //                        ).ToList())
        //    //}).ToList();

        //    return items;
        //}
    }
}
